<?php

namespace app\admin\controller\weixin;

use think\Controller;
use fast\Tree;
use think\db;
/**
 *
 *
 * @icon fa fa-file
 */
class Wxlogin extends Controller
{

    /**
     * Unit模型对象
     */
    private $appid = 'wx2bab6cd1400f48bb';
    private $secret = '2c4eec8b958e7be9c627ac1f369663de';

    protected $model = null;
    protected $noNeedRight=["dologin","hello"];
    protected $noNeedLogin=["dologin","hello"];


    public function _initialize()
    {
        parent::_initialize();
        return true;
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


        /**
         * 添加
         */
        public function dologin(){
        $isNewUser=false;
        // 获取小程序端传来的 code
        $code = $this->request->post('code');
//        $encryptedData = $this->request->post('encryptedData');
//        $iv = $this->request->post('iv');

            if (!$code ) {
                return json([0,
                    'msg' => '缺少必要参数'
                ]);
            }

        // 拼接微信登录接口的 URL
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->appid}&secret={$this->secret}&js_code={$code}&grant_type=authorization_code";

        // 发送 HTTP 请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 禁用SSL证书验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 禁用主机名验证
        $response = curl_exec($ch);
        curl_close($ch);
        file_put_contents('log.txt', $response);
        // 解析返回的 JSON 数据
        $result = json_decode($response, true);
        echolog($result);



        if (isset($result['errcode'])) {
            return json([
                'code' =>0,
                'msg' => '获取 openid 和 session_key 失败: ' . $result['errmsg']
            ]);
        }

        if($result==null) {
            return json([
                'code' => 0,
                'msg' => '连接不上，获取 openid 和 session_key 失败 '
            ]);
        }
        $openid = $result['openid'];
        $session_key = $result['session_key'];


//        // 解密用户信息
//        require_once 'wxBizDataCrypt.php'; // 需要引入微信官方提供的解密类
//        $pc = new \WXBizDataCrypt($this->appid, $session_key);
//        $errCode = $pc->decryptData($encryptedData, $iv, $data);
//
//        if ($errCode != 0) {
//            return json([
//                'code' => 1,
//                'msg' => '用户信息解密失败'
//            ]);
//        }
//
//        $userInfo = json_decode($data, true);
//        $nickName = $userInfo['nickName'];
//        $avatarUrl = $userInfo['avatarUrl'];
//        $gender = $userInfo['gender'];
//
//        // 将用户信息存入数据库
//        $data = [
//            'openid' => $openid,
//            'session_key' => $session_key,
//            'nickname' => $nickName,
//            'avatar' => $avatarUrl,
//            'create_time' => time()
//        ];
//        $user = model('\app\admin\model\User')->where('openid', $openid)->find();

        // 可以将 openid 和 session_key 存储到数据库或缓存中
        // 这里以存储到数据库为例
        $user = model('\app\admin\model\User')->where('openid', $openid)->find();
        if (!$user) {
            // 如果用户不存在，则创建新用户
            $isNewUser=true;
            $data = [
                'openid' => $openid,
                'session_key' => $session_key,
                'createtime' => time(),
                'add_time' => time(),
                'group_id' => 1,
            ];
            Db::name('fa_user')->insert($data);
            $user = model('\app\admin\model\User')->where('openid', $openid)->find();
        } else {
            // 如果用户存在，则更新 session_key
            Db::name('fa_user')->where('openid', $openid)->update([
                'session_key' => $session_key,
                'updatetime' => time()
            ]);
        }
        if($user["mobile"]==""){
            $isNewUser=true;
        }
        echolog(Db::name('fa_user')->getlastsql());
        $oid = $user['openid'];
        $uid = $user ? $user['id'] :  Db::name('fa_user')->getLastInsID();
        $group_id = $user['group_id'];
        $userinfo=array(
            "id"=>$user['id'],
            "user_id"=>$user['id'],
            "username"=>$user['username'],
            "nickname"=>$user['nickname'],
            "score"=>$user['score'],
            "avatar"=>$user['avatar'],
            "mobile"=>$user['mobile'],
            "gender"=>$user['gender'],
            "createtime"=>$user['createtime'],
            "group_id"=>$user['group_id'],
        );
        echolog($uid);
        // 生成包含 oid, uid, group_id, school_id 的验证串
        $authorizationData = [
            'oid' => $oid,
            'uid' => $uid,
            'group_id' => $group_id,
        ];
        $authorization = base64_encode(json_encode($authorizationData));
        echolog($authorizationData);
        // 将验证串存储到缓存中，设置过期时间为 1 小时
        //Cache::set($authorization, $openid, 3600);

        return json([
            'code' => 200,
            'msg' => '登录成功',
            'isNewUser' => $isNewUser,
            'openid' => $openid,
            'userinfo' => $userinfo,
            'authorization' => $authorization
        ]);
    }
}
